package com.strongbj.iot.devices.hr.request.listener;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.command.ActiveMQBytesMessage;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.jms.listener.adapter.MessageListenerAdapter;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.reflect.TypeToken;
import com.strongbj.core.message.MessageHandleContext;
import com.strongbj.iot.devices.hr.message.MQMessageOfHR;
import com.strongbj.iot.devices.hr.request.handle.BuzzerHandle;
import com.strongbj.iot.devices.hr.request.handle.HRControlBuzzerSoundHandle;
import com.strongbj.iot.devices.hr.request.handle.HRResetHandle;

/**
 * 从MQ接收门禁信息的监听类
 * @author yuzhantao
 *
 */
@Component
public class MQMessageOfHRListener  extends MessageListenerAdapter{
	private static Logger logger = LogManager.getLogger(MQMessageOfHRListener.class.getName());
	// 通过策略模式处理不同的信息
	private MessageHandleContext<MQMessageOfHR,Object> messageHandleContent;
	

	public MQMessageOfHRListener(){
		super();
		this.messageHandleContent=new MessageHandleContext<>();
		// 添加消息处理类 ----（蜂鸣器命令的处理）
		this.messageHandleContent.addHandleClass(new BuzzerHandle());
		// 添加消息处理类 ----（重启门禁）
		this.messageHandleContent.addHandleClass(new HRResetHandle());
		// 添加消息处理类 ----（控制蜂鸣器发声）
		this.messageHandleContent.addHandleClass(new HRControlBuzzerSoundHandle());
	}
	
	@JmsListener(destination="HR",concurrency="1")
    public void onMessage(Message message, Session session) throws JMSException {
		if(message instanceof TextMessage){
			TextMessage tm = (TextMessage)message;
			String json = tm.getText();
			MQMessageOfHR rm = JSON.parseObject(json,new TypeToken<MQMessageOfHR>(){}.getType());
			// 智慧档案临时处理方案
			if(rm.getActioncode()==null || rm.getAwsPostdata() == null) {
				JSONObject jsonObject = JSONObject.parseObject(json);
		        String payload = jsonObject.getString("payload");
		        rm = JSON.parseObject(payload, new TypeToken<MQMessageOfHR>(){}.getType());
			}
			this.messageHandleContent.handle(null,rm);
		} else if (message instanceof ActiveMQBytesMessage) {
            ActiveMQBytesMessage bytesMessage = (ActiveMQBytesMessage) message;
            byte[] datas = new byte[(int) bytesMessage.getBodyLength()];
            bytesMessage.readBytes(datas);
            String json = new String(datas);
            MQMessageOfHR rm = JSON.parseObject(json,new TypeToken<MQMessageOfHR>(){}.getType());
			this.messageHandleContent.handle(null,rm);
        } else {
        	logger.info("无法解析的mq对象消息:"+message.getClass().getName());
            return;
        }
    }
}
